local AspireML_Comm = AspireML:NewModule("AspireML_Comm", "AceEvent-3.0", "AceConsole-3.0", "AceComm-3.0" )


function AspireML_Comm:OnInitialize()
	
	
	
end

function AspireML_Comm:OnEnable()
	
	self:RegisterMessage( "AspireML_StartBid", "CommHandler" );
	self:RegisterMessage( "AspireML_StartRoll", "CommHandler" );
	self:RegisterMessage( "AspireML_UpdateBids", "CommHandler" );
	self:RegisterMessage( "AspireML_CloseBid", "CommHandler" );	
	self:RegisterComm("AspireML_StartBid", "CommListener")
	self:RegisterComm("AspireML_StartRoll", "CommListener")
	self:RegisterComm("AspireML_UpdateBids", "CommListener")
	self:RegisterComm("AspireML_CloseBid", "CommListener")
end

function AspireML_Comm:CommHandler( event, arg1, arg2 )

	-- only masterlooter can broadcast
	if not AspireML.masterlooter then return end	
	
	if event == "AspireML_StartBid" then
		self:SendCommMessage( event, arg1, "RAID" )
	
	elseif event == "AspireML_StartRoll" then		
		self:SendCommMessage( event, arg1, "RAID" )
	
	elseif event == "AspireML_UpdateBids" and arg2 then
		self:SendCommMessage( event, arg1 .. " " .. arg2, "RAID" )
		
	elseif event == "AspireML_CloseBid" then
		self:SendCommMessage( event, "", "RAID" )
		
	end
end

function AspireML_Comm:CommListener( prefix, message, distribution, sender )

	-- leave for debugging purposes
	-- if prefix then self:Print( "Comm: " .. prefix  ); end
	-- if distribution then self:Print( "dstr : " .. distribution  ); end
	-- if message then self:Print( "msg: " .. message ); end
	-- if sender then self:Print( "sndr: " .. sender ); end
	
	if AspireML.PLAYERNAME == sender then return end

	if prefix == "AspireML_StartBid" then
		AspireML:SendMessage( "AspireML_StartBid", message )
		
	elseif prefix == "AspireML_StartRoll" then
		AspireML:SendMessage( "AspireML_StartRoll", message )
		
	elseif prefix == "AspireML_UpdateBids" then
		local unitname = string.split(' ', message)	
		local argument = string.sub( message, string.len( unitname ) + 2 )
		
		local entry = {}
		entry.player = unitname
		entry.message = argument
		table.insert( AspireML.bids, entry )
		
		if AspireML.mode == "roll" then
			table.sort(AspireML.bids, function(a,b) return AspireML:SortRolls(a,b) end);
		end
		self:SendMessage( "AspireML_UpdateBids", unitname, argument );		
		
	elseif prefix == "AspireML_CloseBid" then	
		AspireML:SendMessage( "AspireML_CloseBid" )
		
	end
	

end
